package com.doculibre.constellio.connector.twitter.api;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import twitter4j.Paging;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;

/**
 * 
 * Twitter API that enables retrieval of Tweets
 * 
 * @author France Labs
 * 
 */
public class TwitterAPIUtils {


	/**
	 * 
	 * Get Tweets from the Twitter4J API
	 * 
	 * @param twitterAccount where are posted the tweets
	 * @param numMaxTweets is the number of Tweet we want to retrieve
	 * @return list of Tweets
	 * @throws TwitterException
	 */
	public static List<Status> getTweets(String twitterAccount, int numMaxTweets) throws TwitterException {
			return getTweets(twitterAccount, 0, numMaxTweets);
		}

	
	/**
	 * 
	 * Get Tweets from the Twitter4J API
	 * 
	 * @param twitterAccount where are posted the tweets
	 * @param olderThanID is the maxID of the Tweet that will be retrieved (if olderThanID <= 0, no limit will be set)
	 * @param numMaxTweets is the number of Tweet we want to retrieve
	 * @return list of Tweets
	 * @throws TwitterException
	 */
	public static List<Status> getTweets(String twitterAccount, long olderThanID, int numMaxTweets) throws TwitterException {
		Twitter unauthenticatedTwitter = new TwitterFactory().getInstance();
		List<Status> listTweets = new ArrayList<Status>();
		List<Status> statuses;
		Paging paging;
		int totalTweets = 0;
		boolean noMoreTweets = false;
		
		// as the limit in the API is inclusive and that we want an exclusive limit, we decrement the max ID
		olderThanID--;
		
		
		// we retrieve Tweet by page of 200 Tweets, if we reach the maximum of Tweets "numMaxTweets" or if there is no more Tweet to retrieve, we stop the retrieving
		for (int pageNumber = 1; !noMoreTweets && totalTweets < numMaxTweets;pageNumber++) {
			paging = new Paging(pageNumber, numMaxTweets-totalTweets);
			if (olderThanID > 0){
				paging.maxId(olderThanID);
			}
			// get list of Tweet for the current page
			statuses = unauthenticatedTwitter.getUserTimeline(twitterAccount,
					paging);
			totalTweets += statuses.size();
			
			// if no Tweets has been retrieved this time
			if (statuses.size() == 0)
				noMoreTweets = true;
			
			// add the Tweets to the list
			listTweets.addAll(statuses);
			
		}

		return listTweets;

	}

	/**
	 * 
	 * Return the URL of the home page of a specific twitter account
	 * 
	 * @param twitterAccount
	 * @return URL of the Twitter Account Home page
	 * @throws MalformedURLException
	 */
	public static URL getTwitterURL(String twitterAccount)
			throws MalformedURLException {
		URL twitterURL = new URL("http", "twitter.com", "/#!/" + twitterAccount);
		return twitterURL;
	}
}
